package model;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.sql.Date;

import util.JDBCHelper;

public class BookingIO {

	/**
	 * Method for adding a booking to the booking table. All of the data is
	 * supplied for creating the entry.
	 * @param dateOfBooking
	 * @param flightID
	 * @param numOfSeats
	 * @param accountID
	 * @param userID
	 * @param totalCost
	 * @param seatType
	 * @return
	 */
	public boolean addBooking(Timestamp dateOfBooking, int flightID, int numOfSeats,
			int userID, double totalCost, String seatType){
		JDBCHelper jdbc= new JDBCHelper("cse.unl.edu","mrogers" ,"mrogers", "3ZF:ey"); 
		ArrayList<Object> param =  new ArrayList<Object>();
		param.add(dateOfBooking);
		param.add(flightID);
		param.add(numOfSeats);
		param.add(seatType);
		param.add(userID);
		param.add(totalCost);
		boolean added = true;
		try {
			added = jdbc.insertDB("INSERT into bookings (date_of_booking, "
					+ "flight_ids, number_of_seats, seat_type, user_id, "
					+ "total_cost) VALUES" + "(?,?,?,?,?,?)", param);


			jdbc.conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return added;
	}

	/**
	 * Method to get an ArrayList of Bookings based on the given user id. 
	 * @param userID
	 * @return
	 */
	public ArrayList<Booking> getBookings(int userID){
		JDBCHelper jdbc= new JDBCHelper("cse.unl.edu","mrogers" ,"mrogers", "3ZF:ey"); 
		ArrayList<Object> param =  new ArrayList<Object>();
		param.add(userID);
		ResultSet rs = jdbc.queryDB("SELECT * from bookings WHERE user_id=?", param);
		ArrayList<Booking> bookings = new ArrayList<Booking>();
		Booking booking = null;
		try {
			if (rs != null){
				try {
					while(rs.next()){
						int id =rs.getInt("id"); 
						Date dateOfBooking =rs.getDate("date_of_booking"); 
						int flightIds =rs.getInt("flight_ids");
						FlightIO flightIO = new FlightIO();
						Flight flight = flightIO.getFlight(flightIds);
						int numOfSeats =rs.getInt("number_of_seats");
						String seatType = rs.getString("seat_type");
						int userId =rs.getInt("user_id"); 
						double totalCost = rs.getDouble("total_cost");

						booking = new Booking(id, dateOfBooking, flight, 
								numOfSeats, userId, totalCost, seatType);
						bookings.add(booking);
					}
				} catch (SQLException e) {
					e.printStackTrace();
				} 
			}			
			jdbc.conn.close();

		} catch (SQLException e) {
			e.printStackTrace();
		}

		return bookings;
	}

}
